import sched


class Stimulator(object):
    def __init__(self, stim_callback):
        self.sequence = []
        self.T = 0
        self.sche = sched.scheduler()
        self.stim_callback = stim_callback

    def add_stim(self, stim, interval=0, during=0, priority=10):
        self.sequence.append((self.T, stim, interval, during, priority))
        self.T += interval

    def start(self):
        self.sequence.sort(key=lambda i: i[0])
        for i in self.sequence:
            self.sche.enter(i[0], i[4], self.emit, argument=(i[1],))
        self.sche.run(True)

    def emit(self, stim):
        self.stim_callback(stim)

    def stop(self):
        self.stim_callback(None)
        for i in self.sche.queue:
            self.sche.cancel(i)
